package com.shensi.adminCollect.service.markert.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shensi.adminCollect.common.constant.UserConstants;
import com.shensi.adminCollect.common.enums.DecimalConstant;
import com.shensi.adminCollect.common.exception.CustomException;
import com.shensi.adminCollect.common.utils.DateUtils;
import com.shensi.adminCollect.common.utils.LocalDateTimeUtil;
import com.shensi.adminCollect.common.utils.LocalDateUtils;
import com.shensi.adminCollect.domain.customer.ActivityMessagePushRecord;
import com.shensi.adminCollect.service.customer.ActivityMessagePushRecordService;
import com.shensi.adminCollect.domain.markert.ReductionActivity;
import com.shensi.adminCollect.domain.markert.ReductionOilRelations;
import com.shensi.adminCollect.domain.markert.ReductionRules;
import com.shensi.adminCollect.domain.markert.ReductionStationRelations;
import com.shensi.adminCollect.domain.markert.vo.ReductionActivitiesAmountVO;
import com.shensi.adminCollect.domain.markert.vo.ReductionActivitiesVO;
import com.shensi.adminCollect.domain.markert.vo.ReductionActivityVO;
import com.shensi.adminCollect.domain.markert.vo.ReductionDisVo;
import com.shensi.adminCollect.mapper.markert.ReductionActivityMapper;
import com.shensi.adminCollect.mapper.markert.ReductionOilRelationsMapper;
import com.shensi.adminCollect.mapper.markert.ReductionRulesMapper;
import com.shensi.adminCollect.mapper.markert.ReductionStationRelationsMapper;
import com.shensi.adminCollect.service.markert.IReductionActivityService;
import com.shensi.adminCollect.domain.station.Oil;
import com.shensi.adminCollect.domain.station.Station;
import com.shensi.adminCollect.mapper.station.OilMapper;
import com.shensi.adminCollect.mapper.station.StationMapper;
import com.shensi.adminCollect.service.station.IOilService;
import com.shensi.adminCollect.service.station.IStationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * 立减活动Service业务层处理
 * 
 * @author qujia
 * @date 2021-11-03
 */


import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.common.core.domain.entity.SysUser;

@Slf4j
@Service
public class ReductionActivityServiceImpl implements IReductionActivityService
{
    @Autowired
    private ReductionActivityMapper reductionActivityMapper;
    @Autowired
    private ReductionStationRelationsMapper reductionStationRelationsMapper; 
    @Autowired
    private ReductionOilRelationsMapper reductionOilRelationsMapper;
    @Autowired
    private ReductionRulesMapper reductionRulesMapper;
    @Autowired
    private StationMapper stationMapper;
    @Autowired
    private OilMapper oilMapper;
    @Autowired
    private ActivityMessagePushRecordService activityMessagePushRecordService;

    @Resource
    private IStationService stationService;

    @Resource
    private IOilService oilService;

    public static final String OLD_ACTIVITY_CREATE_TIME_STR = "2023-08-05 00:00:00";
    public static final LocalDateTime OLD_ACTIVITY_CREATE_TIME = LocalDateTime.of(2023,8,5,0,0,0);


    /**
     * 查询立减活动
     * 
     * @param activityId 立减活动ID
     * @return 立减活动
     */
    @Override
    public ReductionActivity selectReductionActivityById(Long activityId)
    {
        return reductionActivityMapper.selectReductionActivityById(activityId);
    }

    /**
     * 查询立减活动列表
     * 
     * @param reductionActivity 立减活动
     * @return 立减活动
     */
    @Override
    public List<ReductionActivity> selectReductionActivityList(ReductionActivity reductionActivity)
    {
        return reductionActivityMapper.selectReductionActivityList(reductionActivity);
    }

    /**
     * 新增立减活动
     * 
     * @param reductionActivity 立减活动
     * @return 结果
     */
    @Override
    public int insertReductionActivity(ReductionActivity reductionActivity)
    {
        reductionActivity.setCreateTime(DateUtils.getNowDate());
        return reductionActivityMapper.insertReductionActivity(reductionActivity);
    }

    @Override
    @Transactional
    public Long insertReductionActivity(Map<String, Object> params) throws ParseException {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String requestJson = params.get("requestJson").toString();
        LoginUser currentUser = (LoginUser) params.get("currentUser");
        SysUser user = currentUser.getUser();
        JSONObject jsonObject = JSONObject.parseObject(requestJson);

        ReductionActivity reductionActivity = new ReductionActivity();
        reductionActivity.setActivityId((jsonObject.containsKey("activityId") && !jsonObject.get("activityId").equals(""))
                ?Long.valueOf(jsonObject.get("activityId").toString()):null);
        if(jsonObject.containsKey("timeModes") && jsonObject.get("timeModes") != null){
            JSONArray timeModes = jsonObject.getJSONArray("timeModes");
            if (timeModes.size()!=0) {
                StringJoiner joiner = new StringJoiner(",");
                for (int i = 0; i < timeModes.size(); i++) {
                    joiner.add(timeModes.getString(i));
                }
                reductionActivity.setTimeMode(joiner.toString());
                List<String> daysList = (List<String>) jsonObject.get("days");
                if(daysList != null && daysList.size()>0){
                    String days = String.join(",", daysList);
                    reductionActivity.setDays(days);
                }else{
                    reductionActivity.setDays(StringUtils.EMPTY);
                }
                List<String> weekList = (List<String>) jsonObject.get("weeks");
                if(weekList != null && weekList.size()>0){
                    String weeks = String.join(",", weekList);
                    reductionActivity.setWeeks(weeks);
                }else{
                    reductionActivity.setWeeks(StringUtils.EMPTY);
                }
            }
        }
        if(com.shensi.adminCollect.common.utils.StringUtils.isNotEmpty(jsonObject.getString("amtUpperLimit"))){
            reductionActivity.setAmtUpperLimit(jsonObject.containsKey("amtUpperLimit")?new BigDecimal(jsonObject.getString("amtUpperLimit")):null);
        }

        reductionActivity.setActiveStatus("1");
        reductionActivity.setEnterpriseId(user.getEnterpriseId());
        reductionActivity.setCardFlag(jsonObject.containsKey("cardFlag")?jsonObject.getString("cardFlag"):null);
        reductionActivity.setActivityName(jsonObject.containsKey("activityName")?jsonObject.getString("activityName"):null);
        reductionActivity.setActivityUse(jsonObject.containsKey("activityUse")?jsonObject.getString("activityUse"):null);
        reductionActivity.setActivityType(jsonObject.containsKey("activityType")?jsonObject.getString("activityType"):null);
        reductionActivity.setActivityMode(jsonObject.containsKey("activityMode")?jsonObject.getString("activityMode"):null);
        reductionActivity.setActivityUse(jsonObject.containsKey("activityUse")?jsonObject.getString("activityUse"):null);
        reductionActivity.setOilPartOrAll(jsonObject.containsKey("oilPartOrAll")?(jsonObject.getString("oilPartOrAll").equals("true")?1L:0L):null);
        reductionActivity.setMemberCondition(jsonObject.containsKey("memberCondition")?jsonObject.getString("memberCondition"):null);
        reductionActivity.setWeekTimeRangeType(jsonObject.containsKey("weekTimeRangeType")?jsonObject.getString("weekTimeRangeType"):null);
        reductionActivity.setMonthTimeRangeType(jsonObject.containsKey("monthTimeRangeType")?jsonObject.getString("monthTimeRangeType"):null);

        if (jsonObject.containsKey("memberLevels") && jsonObject.get("memberLevels") != null) {
            JSONArray memberLevels = jsonObject.getJSONArray("memberLevels");
            if (memberLevels.size()!=0) {
                StringJoiner joiner = new StringJoiner(",");
                for (int i = 0; i < memberLevels.size(); i++) {
                    String level = memberLevels.getString(i);
                    if (StringUtils.equals("99",level)) {
                        // 过滤掉99，之前的旧数据需要过滤掉不保存
                        continue;
                    }
                    joiner.add(level);
                }
                reductionActivity.setMemberLevel(joiner.toString());
            }else{
                reductionActivity.setMemberLevel(StringUtils.EMPTY);
            }
        }else{
            reductionActivity.setMemberLevel(StringUtils.EMPTY);
        }
        if (jsonObject.containsKey("memberTags") && jsonObject.get("memberTags") != null) {
            String memberTags = jsonObject.getString("memberTags");
            reductionActivity.setMemberTags(memberTags);
        }
        reductionActivity.setPaymentMethod(getJsonArrayStr(jsonObject,"paymentMethods",StringUtils.EMPTY));
        reductionActivity.setMemberCategory(getJsonArrayStr(jsonObject,"memberCategories",StringUtils.EMPTY));
        reductionActivity.setCardType(getJsonArrayStr(jsonObject,"cardTypes",StringUtils.EMPTY));
        reductionActivity.setPhysicalCardType(getJsonArrayStr(jsonObject,"physicalCardTypes",StringUtils.EMPTY));
        //reductionActivity.setPaymentMethod(jsonObject.containsKey("paymentMethod")?jsonObject.getString("paymentMethod"):null);
        //reductionActivity.setMemberLevel(jsonObject.containsKey("memberLevel")?jsonObject.getString("memberLevel"):null);
        //reductionActivity.setMemberTags(jsonObject.containsKey("memberTags")?jsonObject.getString("memberTags"):null);

        reductionActivity.setStartDate(jsonObject.containsKey("startdate")?fmt.parse(jsonObject.get("startdate").toString()):null);
        reductionActivity.setEndDate(jsonObject.containsKey("enddate")?fmt.parse(jsonObject.get("enddate").toString()):null);
        reductionActivity.setMaxCount(jsonObject.containsKey("maxCount")?Long.valueOf(jsonObject.getString("maxCount")):null);
        reductionActivity.setActivityRule(jsonObject.containsKey("activityRule")?jsonObject.getString("activityRule"):null);
        reductionActivity.setBudget((jsonObject.containsKey("budget") && jsonObject.get("budget") != null && !jsonObject.get("budget").equals(""))?
                Double.valueOf(jsonObject.get("budget").toString()):null);
        reductionActivity.setAntiCheating(jsonObject.containsKey("antiCheating")?jsonObject.getString("antiCheating"):null);
        reductionActivity.setCountOfDay((jsonObject.containsKey("countOfDay") && jsonObject.get("countOfDay") != null && !jsonObject.get("countOfDay").equals(""))
                ?Long.valueOf(jsonObject.getString("countOfDay")):null);
        reductionActivity.setCreateUser(user.getUserId());
        reductionActivity.setCreateTime(new Date());
        reductionActivity.setModifyUser(user.getUserId());
        reductionActivity.setModifyTime(new Date());
        String startTimeOfWeek = jsonObject.getString("startTimeOfWeek");
        String endTimeOfWeek = jsonObject.getString("endTimeOfWeek");
        String startTimeOfMonth = jsonObject.getString("startTimeOfMonth");
        String endTimeOfMonth = jsonObject.getString("endTimeOfMonth");
        reductionActivity.setStartTimeOfWeek(StringUtils.isNotBlank(startTimeOfWeek) ? LocalTime.parse(startTimeOfWeek):null);
        reductionActivity.setEndTimeOfWeek(StringUtils.isNotBlank(endTimeOfWeek) ? LocalTime.parse(endTimeOfWeek):null);
        reductionActivity.setStartTimeOfMonth(StringUtils.isNotBlank(startTimeOfMonth) ? LocalTime.parse(startTimeOfMonth):null);
        reductionActivity.setEndTimeOfMonth(StringUtils.isNotBlank(endTimeOfMonth) ? LocalTime.parse(endTimeOfMonth):null);
        reductionActivity.setActivityEnabled(jsonObject.getString("activityEnabled"));
        reductionActivity.setRechargeActivityRechargeEnable(jsonObject.getInteger("rechargeActivityRechargeEnable"));
        reductionActivity.setRechargeActivityConsumeEnable(jsonObject.getInteger("rechargeActivityConsumeEnable"));
        if(reductionActivity.getActivityId() != null){
            ReductionActivity oldActivity = reductionActivityMapper.selectReductionActivityById(reductionActivity.getActivityId());
            if (oldActivity == null) {
                throw new CustomException("活动不存在");
            }
            if (StringUtils.equals("1",oldActivity.getActivityEnabled())) {
                throw new CustomException("活动已启用，不可修改");
            }
            //修改
            reductionActivityMapper.updateReductionActivity(reductionActivity);
            //删除中间表
            reductionStationRelationsMapper.deleteReductionStationRelationsByActivityId(reductionActivity.getActivityId());
            reductionRulesMapper.deleteReductionRulesByActivityId(reductionActivity.getActivityId());
            ReductionOilRelations reductionOilRelations = new ReductionOilRelations();
            reductionOilRelations.setActivityId(reductionActivity.getActivityId());
            List<ReductionOilRelations> reductionOilRelationsList = reductionOilRelationsMapper.selectReductionOilRelationsList(reductionOilRelations);
            for (ReductionOilRelations oilRelations : reductionOilRelationsList) {
                reductionRulesMapper.deleteReductionRulesByActivityOilId(oilRelations.getActivityOilId());
                reductionOilRelationsMapper.deleteReductionOilRelationsById(oilRelations.getActivityOilId());
            }

        }else {
            //新增
            reductionActivity.setActivityEnabled("0"); // 新增默认不启用
            reductionActivityMapper.insertReductionActivity(reductionActivity);
        }
        List<Map<String,Object>> selectStationList = (List<Map<String,Object>>) jsonObject.get("selectStationList");
        if(selectStationList != null && selectStationList.size()>0){
            ReductionStationRelations reductionStationRelations = null;
            for (Map<String,Object> stationMap : selectStationList) {
                reductionStationRelations = new ReductionStationRelations();
                reductionStationRelations.setActivityId(reductionActivity.getActivityId());
                reductionStationRelations.setStationId(Long.valueOf(stationMap.get("stationId").toString()));
                reductionStationRelationsMapper.insertReductionStationRelations(reductionStationRelations);
            }
        }
        List<Map<String,Object>> selectOilList = (List<Map<String,Object>>) jsonObject.get("selectOilList");
        if(selectOilList != null && selectOilList.size()>0){
            ReductionOilRelations reductionOilRelations = null;
            for (Map<String,Object> oilMap : selectOilList) {
                reductionOilRelations = new ReductionOilRelations();
                reductionOilRelations.setActivityId(reductionActivity.getActivityId());
                reductionOilRelations.setOilId(Long.valueOf(oilMap.get("oilId").toString()));
                reductionOilRelationsMapper.insertReductionOilRelations(reductionOilRelations);
                if(reductionActivity.getOilPartOrAll() == 0L){
                    //部分油品单独维护
                    List<Map<String,Object>> rules = (List<Map<String,Object>>) oilMap.get("rules");
                    ReductionRules reductionRules = null;
                    for (Map<String, Object> ruleMap : rules) {
                        reductionRules = new ReductionRules();
                        reductionRules.setActivityOilId(reductionOilRelations.getActivityOilId());
                        Long budget = (ruleMap.containsKey("budget") && ruleMap.get("budget") != null && !ruleMap.get("budget").equals(""))?Long.valueOf(ruleMap.get("budget").toString()):null;
                        reductionRules.setFull((ruleMap.containsKey("full") && ruleMap.get("full") != null && !ruleMap.get("full").equals(""))?Double.valueOf(ruleMap.get("full").toString()):null);
                        reductionRules.setCut((ruleMap.containsKey("cut") && ruleMap.get("cut") != null && !ruleMap.get("cut").equals(""))?Double.valueOf(ruleMap.get("cut").toString()):null);
                        reductionRules.setCutMax((ruleMap.containsKey("cutMax") && ruleMap.get("cutMax") != null && !ruleMap.get("cutMax").equals(""))?Double.valueOf(ruleMap.get("cutMax").toString()):null);
                        reductionRules.setCutMin((ruleMap.containsKey("cutMin") && ruleMap.get("cutMin") != null && !ruleMap.get("cutMin").equals(""))?Double.valueOf(ruleMap.get("cutMin").toString()):null);
                        reductionRulesMapper.insertReductionRules(reductionRules);
                    }
                }
            }
        }
        if(reductionActivity.getOilPartOrAll() == 1L){
            List<Map<String,Object>> rules = (List<Map<String,Object>>) jsonObject.get("rules");
            ReductionRules reductionRules = null;
            for (Map<String, Object> ruleMap : rules) {
                reductionRules = new ReductionRules();
                reductionRules.setActivityId(reductionActivity.getActivityId());
                reductionRules.setFull((ruleMap.containsKey("full") && !ruleMap.get("full").equals(""))?Double.valueOf(ruleMap.get("full").toString()):null);
                reductionRules.setCut((ruleMap.containsKey("cut") && !ruleMap.get("cut").equals(""))?Double.valueOf(ruleMap.get("cut").toString()):null);
                reductionRules.setCutMax((ruleMap.containsKey("cutMax") && !ruleMap.get("cutMax").equals(""))?Double.valueOf(ruleMap.get("cutMax").toString()):null);
                reductionRules.setCutMin((ruleMap.containsKey("cutMin") && !ruleMap.get("cutMin").equals(""))?Double.valueOf(ruleMap.get("cutMin").toString()):null);
                reductionRulesMapper.insertReductionRules(reductionRules);
            }
        }
        return reductionActivity.getActivityId();
    }

    /**
     * 查询立减活动的完整信息
     *
     * @param activityId 立减活动Id
     * @return 结果
     */
    @Override
    public Map<String,Object> selectActivityInfoByActivityId(Long activityId)
    {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        ReductionActivity reductionActivity = reductionActivityMapper.selectReductionActivityById(activityId);
        ReductionStationRelations reductionStationRelations = new ReductionStationRelations();
        reductionStationRelations.setActivityId(activityId);
        List<ReductionStationRelations> reductionStationRelationsList = reductionStationRelationsMapper.selectReductionStationRelationsList(reductionStationRelations);
        List<Station> selectStationList = new ArrayList<Station>();
        List<JSONObject> selectOilList = new ArrayList<JSONObject>();
        for (ReductionStationRelations stationRelations : reductionStationRelationsList) {
            selectStationList.add(stationMapper.selectStationById(stationRelations.getStationId()));
        }
        ReductionOilRelations reductionOilRelations = new ReductionOilRelations();
        reductionOilRelations.setActivityId(activityId);
        List<ReductionOilRelations> reductionOilRelationsList = reductionOilRelationsMapper.selectReductionOilRelationsList(reductionOilRelations);
        for (ReductionOilRelations oilRelations : reductionOilRelationsList) {
            Oil oil = oilMapper.selectOilById(oilRelations.getOilId());
            JSONObject oilMap = (JSONObject) JSONObject.toJSON(oil);
            ReductionRules reductionRules = new ReductionRules();
            reductionRules.setActivityOilId(oilRelations.getActivityOilId());
            List<ReductionRules> reductionRulesList = reductionRulesMapper.selectReductionRulesList(reductionRules);
            oilMap.put("rules",reductionRulesList);
            selectOilList.add(oilMap);
        }
        ReductionRules reductionRules = new ReductionRules();
        reductionRules.setActivityId(activityId);
        List<ReductionRules> reductionRulesList = reductionRulesMapper.selectReductionRulesList(reductionRules);
        ModelMapper mapper = new ModelMapper();
        resultMap.put("reductionActivity", ReductionActivityVO.DOtoVO(mapper,reductionActivity));
        resultMap.put("selectOilList",selectOilList);
        resultMap.put("selectStationList",selectStationList);
        resultMap.put("reductionRulesList",reductionRulesList);
        String[] days = new String[0];
        if(StringUtils.isNotBlank(reductionActivity.getDays())){
            days = reductionActivity.getDays().split(",");
        }
        resultMap.put("days",days);
        String[] weeks = new String[0];
        if(StringUtils.isNotBlank((reductionActivity.getWeeks()))){
            weeks = reductionActivity.getWeeks().split(",");
        }
        resultMap.put("weeks",weeks);

        ActivityMessagePushRecord pushRecord=new ActivityMessagePushRecord();
        pushRecord.setBusinessId(activityId);
        pushRecord.setBusinessName(ActivityMessagePushRecord.REDUCTION_ACTIVITY);
        List<ActivityMessagePushRecord> records=activityMessagePushRecordService.query(pushRecord);
        if(records.size()>0){
            ActivityMessagePushRecord record = records.get(0);
            resultMap.put("sendFlag",record.getSendFlag());
            resultMap.put("wxContent",record.getContent());
        }else{
            resultMap.put("sendFlag",0);
        }
        return resultMap;
    }

    /**
     * 修改立减活动
     * 
     * @param reductionActivity 立减活动
     * @return 结果
     */
    @Override
    public int updateReductionActivity(ReductionActivity reductionActivity)
    {
        return reductionActivityMapper.updateReductionActivity(reductionActivity);
    }

    /**
     * 批量删除立减活动
     * 
     * @param activityIds 需要删除的立减活动ID
     * @return 结果
     */
    @Override
    public int deleteReductionActivityByIds(Long[] activityIds)
    {
        return reductionActivityMapper.deleteReductionActivityByIds(activityIds);
    }

    /**
     * 删除立减活动信息
     * 
     * @param activityId 立减活动ID
     * @return 结果
     */
    @Override
    public int deleteReductionActivityById(Long activityId)
    {
        return reductionActivityMapper.deleteReductionActivityById(activityId);
    }

    /**
     * 根据登录用户查询立减活动
     * @param activity
     * @return
     */
    @Override
    public List<ReductionActivity> selectActivityByLoginUser(ReductionActivity activity) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        activity.setActiveStatus("1");
        activity.setEnterpriseId(currentUser.getUser().getEnterpriseId());
        String userLevel = currentUser.getUser().getUserLevel();
        if(StringUtils.equals(UserConstants.LEVEL_THREE,userLevel)){
            return reductionActivityMapper.selectByStationId(activity,currentUser.getUser().getStationId());
        }
        return selectReductionActivityList(activity);
    }

    @Override
    public ReductionDisVo selectReductionAmt(String amt, String stationId, String oilName, String oilLiters, String mobilePhone) {
        if(new BigDecimal(amt).compareTo(BigDecimal.ZERO) < 0){
            throw new CustomException("订单金额不能小于0");
        }

        ReductionActivitiesVO activitiesVO=new ReductionActivitiesVO();
        activitiesVO.setActivityUse("CSP");
        activitiesVO.setAmt(new BigDecimal(amt));
        activitiesVO.setDateTime(LocalDateTimeUtil.parse(LocalDateTime.now()));

        Station station = stationService.selectStationById(Long.valueOf(stationId));

        activitiesVO.setEnterpriseId(station.getEnterpriseId().intValue());

        //oilname转OilId
        Oil oil = oilMapper.selectOilByName(oilName);
        activitiesVO.setOilId(oil.getOilId().intValue());
        activitiesVO.setOrderLiters(oilLiters);
        activitiesVO.setStationId(Integer.valueOf(stationId));
//        BigDecimal discountAmt = reductionActivitiesAmountCalculation(activitiesVO).setScale(2, RoundingMode.HALF_UP);

        ReductionDisVo reductionDisVo = reductionActivitiesAmountCalculation(activitiesVO);

        BigDecimal discountAmt = Objects.isNull(reductionDisVo.getDiscountAmt()) ? BigDecimal.ZERO : reductionDisVo.getDiscountAmt().setScale(2, RoundingMode.HALF_UP);

        BigDecimal amtFin = new BigDecimal(amt);
        if(amtFin.subtract(discountAmt).compareTo(DecimalConstant.O_01)<=0) {
            //amt=BigDecimal.valueOf(0.01);
            discountAmt = amtFin.subtract(DecimalConstant.O_01);
            reductionDisVo.setDiscountAmt(discountAmt);
        }
//        if(activitiesVO.getActivityId()!=null) {
//            //更新活动的预算，避免多个用户同时支付时，产生超预算的问题
//            reductionActivityMapper.updateReductionActivityBudget(discountAmt.negate(), activitiesVO.getActivityId());
//        }
        return reductionDisVo;
    }

    public ReductionDisVo reductionActivitiesAmountCalculation(ReductionActivitiesVO reductionActivitiesVO) {
        //计算当前是周几以及几号，查询时间是否符合
        BigDecimal finalDeductionAmount=BigDecimal.ZERO;//最后可以被扣除的金额
        ReductionDisVo finalDeduction = new ReductionDisVo();
        log.info("开始进行立减，计算金额");
        Calendar calendar = Calendar.getInstance();
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        int month = calendar.get(Calendar.DAY_OF_MONTH);
        if(week == 1){
            week = 7;
        }else{
            week--;
        }
        List<ReductionActivitiesAmountVO> acticity=reductionActivityMapper.selectReductionActivityStationId(reductionActivitiesVO);
        for(ReductionActivitiesAmountVO amoutv0:acticity) {

            //判断实付金额是否超过上限门槛
            if(amoutv0.getAmtUpperLimit()!=null&&amoutv0.getAmtUpperLimit().compareTo(reductionActivitiesVO.getAmt())==-1){
                continue;
            }

            LocalDateTime modifyTime = LocalDateUtils.dateToLocalDateTime(amoutv0.getModifyTime());
            if(modifyTime.isBefore(ReductionActivityServiceImpl.OLD_ACTIVITY_CREATE_TIME)){
                //老活动逻辑
                //查看是否适用当前时间 生效时间段 all：全部时间段  week：按周选择 month：按月选择
                if(amoutv0.getTimeMode().equals("week") && amoutv0.getDays().contains(String.valueOf(week))) {
                    finalDeductionAmount=sumCountActivityMethods(amoutv0, finalDeductionAmount, reductionActivitiesVO);
                    finalDeduction.setDiscountAmt(finalDeductionAmount);
                    finalDeduction.setActivityId(amoutv0.getActivityId());

                }else if(amoutv0.getTimeMode().equals("month") && amoutv0.getDays().contains(String.valueOf(month))) {
                    finalDeductionAmount=sumCountActivityMethods(amoutv0, finalDeductionAmount, reductionActivitiesVO);
                    finalDeduction.setDiscountAmt(finalDeductionAmount);
                    finalDeduction.setActivityId(amoutv0.getActivityId());
                }else if (amoutv0.getTimeMode().equals("all") ){
                    //不是按周 按月，就一定是全部时间段生效
                    finalDeductionAmount=sumCountActivityMethods(amoutv0, finalDeductionAmount, reductionActivitiesVO);
                    finalDeduction.setDiscountAmt(finalDeductionAmount);
                    finalDeduction.setActivityId(amoutv0.getActivityId());
                }
            }else{
                //新活动逻辑
                if("all".equals(amoutv0.getTimeMode())){
                    //全部时间
                    finalDeductionAmount = sumCountActivityMethods(amoutv0,finalDeductionAmount,reductionActivitiesVO);
                    finalDeduction.setDiscountAmt(finalDeductionAmount);
                    finalDeduction.setActivityId(amoutv0.getActivityId());
                }else{
                    String days = amoutv0.getDays();
                    String weeks = amoutv0.getWeeks();
                    if(StringUtils.contains(days,String.valueOf(month)) || StringUtils.contains(weeks,String.valueOf(week))){
                        finalDeductionAmount = sumCountActivityMethods(amoutv0,finalDeductionAmount,reductionActivitiesVO);
                        finalDeduction.setDiscountAmt(finalDeductionAmount);
                        finalDeduction.setActivityId(amoutv0.getActivityId());
                    }
                }
            }

        }

        return finalDeduction;
    }

    private BigDecimal sumCountActivityMethods(ReductionActivitiesAmountVO amoutv0,BigDecimal finalDeductionAmount,ReductionActivitiesVO reductionActivitiesVO) {
        ReductionRules reductionRules=new ReductionRules();
        List<ReductionRules> reductionList=new ArrayList<ReductionRules>();
        if(amoutv0.getOilPartOrAll() == 1) {
            //针对全部油品，规则直接关联活动
            reductionRules.setActivityId(amoutv0.getActivityId().longValue());
            reductionList=reductionRulesMapper.selectReductionRulesList(reductionRules);
        }else {
            //针对部分油品，规则关联油品
            reductionRules.setActivityOilId(new Long(amoutv0.getActivityOilId()));
            reductionList=reductionRulesMapper.selectReductionRulesList(reductionRules);
        }

        //对活动的具体内容开始计算，判断是哪种活动
//        ReductionDisVo reductionDisVo = new ReductionDisVo();

        for(ReductionRules rules:reductionList) {
            BigDecimal amtBigd=BigDecimal.ZERO;		//临时金额
            BigDecimal orderLiters=BigDecimal.ZERO;	//加油的升数
            //活动类型
            switch (amoutv0.getActivityType()) {
                case "AAL":
                    log.info("立减活动------每升立减");
                    //每升立减 随机立减（满足x金额才能触发 每升立减活动 随机数在区间内进行随机）
                    //每升立减 百分比立减
                    //每升立减 定额立减
                    finalDeductionAmount=countActivityMethods(rules, amoutv0, reductionActivitiesVO, finalDeductionAmount);
//                    reductionDisVo.setDiscountAmt(finalDeductionAmount);
//                    reductionDisVo.setActivityId(amoutv0.getActivityId());
                    break;
                case "LOR":
                    //按固定数量 随机立减（满足x金额才能触发 每升立减活动 随机数在区间内进行随机）
                    //按固定数量 百分比立减
                    //按固定数量 定额立减
                    log.info("立减活动------固定数量");
                    switch (amoutv0.getActivityMode()) {
                        case "RDD":
                            Double random = Math.random()*rules.getCutMax()+rules.getCutMin();//随机数
                            if(random > rules.getCutMax()) random = rules.getCutMax();
                            //满足多少升条件则 总共扣除金额=随机立减
                            orderLiters=new BigDecimal(reductionActivitiesVO.getOrderLiters());
                            if(orderLiters.compareTo(BigDecimal.valueOf(rules.getFull()))>=0) {
                                amtBigd=BigDecimal.valueOf(random);
                            }
                            //判断是否超过了活动预算
                            if(new BigDecimal(random).compareTo(amoutv0.getBudget())==1) {
                                amtBigd=amoutv0.getBudget().compareTo(BigDecimal.ZERO)==1?amoutv0.getBudget():BigDecimal.ZERO;
                            }
                            if(finalDeductionAmount.compareTo(amtBigd)==-1) {
                                finalDeductionAmount=amtBigd;
                                reductionActivitiesVO.setActivityId(amoutv0.getActivityId().intValue());
//                                reductionDisVo.setDiscountAmt(finalDeductionAmount);
//                                reductionDisVo.setActivityId(amoutv0.getActivityId());
                            }
                            break;
                        case "PAR":
                            //满足多少升条件则 总共扣除金额=原始金额*百分比
                            orderLiters=new BigDecimal(reductionActivitiesVO.getOrderLiters());
                            if(orderLiters.compareTo(BigDecimal.valueOf(rules.getFull()))>=0) {
                                amtBigd=BigDecimal.valueOf(rules.getCut()).multiply(BigDecimal.valueOf(0.01)).multiply(reductionActivitiesVO.getAmt()) ;
                            }
                            if(finalDeductionAmount.compareTo(amtBigd)==-1) {
                                finalDeductionAmount=amtBigd;
                                reductionActivitiesVO.setActivityId(amoutv0.getActivityId().intValue());
//                                reductionDisVo.setDiscountAmt(finalDeductionAmount);
//                                reductionDisVo.setActivityId(amoutv0.getActivityId());
                            }
                            break;
                        case "FAD":
                            //满足多少升条件则 总共扣除金额=固定金额
                            orderLiters=new BigDecimal(reductionActivitiesVO.getOrderLiters());
                            if(orderLiters.compareTo(BigDecimal.valueOf(rules.getFull()))>=0) {
                                amtBigd=BigDecimal.valueOf(rules.getCut());
                            }
                            if(finalDeductionAmount.compareTo(amtBigd)==-1) {
                                finalDeductionAmount=amtBigd;
                                reductionActivitiesVO.setActivityId(amoutv0.getActivityId().intValue());
//                                reductionDisVo.setDiscountAmt(finalDeductionAmount);
//                                reductionDisVo.setActivityId(amoutv0.getActivityId());
                            }
                            break;
                        default:
                            log.info("LOR 没有找到活动方式");
                            break;
                    }
                    break;
                case "RFA":
                    log.info("立减活动------固定金额");
                    //按固定金额 随机立减（满足x金额才能触发 随机数在区间内进行随机）
                    //按固定金额 百分比立减
                    //按固定金额 定额立减
                    amtBigd=BigDecimal.ZERO;
                    orderLiters=BigDecimal.ZERO;
                    switch (amoutv0.getActivityMode()) {
                        case "RDD":
                            log.info("立减活动------随机立减");
                            Double random = Math.random()*rules.getCutMax()+rules.getCutMin();//随机数
                            if(random > rules.getCutMax()) random = rules.getCutMax();
                            if(reductionActivitiesVO.getAmt().compareTo(BigDecimal.valueOf(rules.getFull()))>=0) {
                                amtBigd=BigDecimal.valueOf(random);
                            }
                            //判断是否超过了活动预算
                            if(new BigDecimal(random).compareTo(amoutv0.getBudget())==1) {
                                amtBigd=amoutv0.getBudget().compareTo(BigDecimal.ZERO)==1?amoutv0.getBudget():BigDecimal.ZERO;
                            }
                            if(finalDeductionAmount.compareTo(amtBigd)==-1) {
                                finalDeductionAmount=amtBigd;
                                reductionActivitiesVO.setActivityId(amoutv0.getActivityId().intValue());
//                                reductionDisVo.setDiscountAmt(finalDeductionAmount);
//                                reductionDisVo.setActivityId(amoutv0.getActivityId());
                            }
                            break;
                        case "PAR":
                            log.info("立减活动------百分比立减");
                            //满足达标金额 总共扣除金额=百分比*原始金额
                            if(reductionActivitiesVO.getAmt().compareTo(BigDecimal.valueOf(rules.getFull()))>=0) {
                                amtBigd=reductionActivitiesVO.getAmt().multiply(BigDecimal.valueOf(0.01)).multiply(BigDecimal.valueOf(rules.getCut()));
                            }
                            if(finalDeductionAmount.compareTo(amtBigd)==-1) {
                                finalDeductionAmount=amtBigd;
                                reductionActivitiesVO.setActivityId(amoutv0.getActivityId().intValue());
//                                reductionDisVo.setDiscountAmt(finalDeductionAmount);
//                                reductionDisVo.setActivityId(amoutv0.getActivityId());
                            }
                            break;
                        case "FAD":
                            log.info("立减活动------定额立减");
                            //满足达标金额总共扣除金额=定额
                            if(reductionActivitiesVO.getAmt().compareTo(BigDecimal.valueOf(rules.getFull()))>=0) {
                                amtBigd=BigDecimal.valueOf(rules.getCut());
                            }
                            if(finalDeductionAmount.compareTo(amtBigd)==-1) {
                                finalDeductionAmount=amtBigd;
                                reductionActivitiesVO.setActivityId(amoutv0.getActivityId().intValue());
//                                reductionDisVo.setDiscountAmt(finalDeductionAmount);
//                                reductionDisVo.setActivityId(amoutv0.getActivityId());
                            }
                            break;
                        default:
                            log.info("RFA 没有找到活动方式");
                            break;
                    }
                    break;
                default:
                    log.info("没有找到活动类型");
                    break;
            }
        }
        return finalDeductionAmount;
    }


    private BigDecimal countActivityMethods(ReductionRules rules,ReductionActivitiesAmountVO amoutv0,
                                            ReductionActivitiesVO reductionActivitiesVO,BigDecimal amtBig) {
        BigDecimal amtBigd=BigDecimal.ZERO;
        switch (amoutv0.getActivityMode()) {
            case "RDD":
                Double random = Math.random()*rules.getCutMax()+rules.getCutMin();//随机数
                if(random > rules.getCutMax()) random = rules.getCutMax();
//			if(random < rules.getCutMin()) random = rules.getCutMin();
                //每升立减活动（满足x金额才能触发 每升立减活动 随机数在区间内进行随机）
                if(reductionActivitiesVO.getAmt().compareTo(BigDecimal.valueOf(rules.getFull()))>=0) {
                    amtBigd=new BigDecimal(reductionActivitiesVO.getOrderLiters()).setScale(0, BigDecimal.ROUND_DOWN).multiply(BigDecimal.valueOf(random));
                }

                //判断是否超过了活动预算
                if(new BigDecimal(random).compareTo(amoutv0.getBudget())==1) {
                    amtBigd=amoutv0.getBudget().compareTo(BigDecimal.ZERO)==1?amoutv0.getBudget():BigDecimal.ZERO;
                }

                if(amtBig.compareTo(amtBigd)==-1) {
                    amtBig=amtBigd;
                    reductionActivitiesVO.setActivityId(amoutv0.getActivityId().intValue());
                }
                break;
            case "PAR":
                //总共扣除金额=百分比*单价
                //计算单价=总金额/总升
                if (rules.getFull() ==null || reductionActivitiesVO.getAmt().compareTo(BigDecimal.valueOf(rules.getFull())) >= 0) {
                    amtBigd=reductionActivitiesVO.getAmt().multiply(BigDecimal.valueOf(rules.getCut())).multiply(BigDecimal.valueOf(0.01)).setScale(2, RoundingMode.DOWN);
                    if(amtBig.compareTo(amtBigd)==-1) {
                        amtBig=amtBigd;
                        reductionActivitiesVO.setActivityId(amoutv0.getActivityId().intValue());
                    }
                }
                break;
            case "FAD":
                //总共扣除金额=每升*定额
                if (rules.getFull() ==null || reductionActivitiesVO.getAmt().compareTo(BigDecimal.valueOf(rules.getFull())) >= 0) {
                    amtBigd=new BigDecimal(reductionActivitiesVO.getOrderLiters()).multiply(BigDecimal.valueOf(rules.getCut()));
                    if(amtBig.compareTo(amtBigd)==-1) {
                        amtBig=amtBigd;
                        reductionActivitiesVO.setActivityId(amoutv0.getActivityId().intValue());
                    }
                }
                break;
            default:
                log.info("AAL 未查询到活动方式");
                break;
        }
        return amtBig;
    }

    @Override
    public int changeActivityEnabled(Long id) {
        ReductionActivity reductionActivity = reductionActivityMapper.selectReductionActivityById(id);
        if (reductionActivity == null) {
            return 0;
        }
        LoginUser user = SecurityUtils.getLoginUser();
        Long userId = user.getUser().getUserId();
        log.info("立减活动状态修改,id:[{}],name:[{}],userId:[{}]",reductionActivity.getActivityId(),reductionActivity.getActivityName(), userId);
        ReductionActivity update = new ReductionActivity();
        update.setActivityId(reductionActivity.getActivityId());
        update.setModifyTime(new Date());
        update.setModifyUser(userId);
        String activityEnabled = reductionActivity.getActivityEnabled();
        if (StringUtils.equals("1",activityEnabled)) {
            update.setActivityEnabled("0");
        }else{
            update.setActivityEnabled("1");
        }
        return reductionActivityMapper.updateReductionActivity(update);
    }

    private String getJsonArrayStr(JSONObject object,String field,String def){
        if (object.get(field) != null) {
            JSONArray jsArr = object.getJSONArray(field);
            if (jsArr.size()!=0) {
                StringJoiner joiner = new StringJoiner(",");
                for (int i = 0; i < jsArr.size(); i++) {
                    joiner.add(jsArr.getString(i));
                }
                return joiner.toString();
            }
        }
        return def;
    }
}
